package com.atguigu.designpattern.singleton.type6;

public class SingletonTest06 {

    public static void main(String[] args) {
        System.out.println("单例模式-懒汉式-双重检查，推荐！！");
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();

        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1 hashcode" + singleton1.hashCode());
        System.out.println("singleton2 hashcode" + singleton2.hashCode());

    }

}

class Singleton{

    //1、构造器私有化，外部不能new
    private Singleton() {

    }

    //2、本类内部定义对象实例，使用volatile刷新对象状态到主存
    private  static volatile Singleton instance ;

    // 提供一个静态的公共方法，加入了双重检查代码，解决现场安全问题，同时解决懒加载问题
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
